﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cherry.Agile.Framework.Cache;
using Cherry.Agile.Core;
using Microsoft.Practices.Unity;
using System.Runtime.Caching;

namespace Cherry.Agile.Security
{
    /// <summary>
    /// 默认权限缓存槽
    /// </summary>
    public class DefatultCacheStorage : ICacheStorage
    {
        const string Cache_Name = "distributed";
        /// <summary>
        /// 
        /// </summary>
        protected virtual TimeSpan ItemExpiration
        {
            get
            {
                return  TimeSpan.FromMinutes(25);
            }
        }
        ICache _cache;
        /// <summary>
        /// 
        /// </summary>
        [Dependency]
        public ITokenProvider TokenProvider { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DefatultCacheStorage( )
        {
            _cache = Cherry.Agile.Framework.Cache.CacheManager.GetCache(Cache_Name);
          
            if (_cache == null)
            {
                throw new ArgumentNullException("invalid authorization cache storage config setting");
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual object this[string key]
        {
            get
            {
                var newKey = GetKey(key);

                if (!string.IsNullOrEmpty(newKey))
                    return _cache.Get(newKey);
                else
                    return null;
            }

            set
            {
                var newKey = GetKey(key);
                if (!string.IsNullOrEmpty(newKey))
                {
                    if (_cache.Contains(newKey))
                        _cache.Remove(newKey);
                    if (value != null)
                    {
                        _cache.Add(newKey, value,ItemExpiration);
                    }
                }

            }
        }
        
        private string GetKey(string key)
        {
            var token = TokenProvider.GetCurrentToken();
            if (token == null)
                return null;
            string prifix = token.Value.Identity;
            if (string.IsNullOrEmpty(prifix))
                return string.Empty;
            
            var tiket = token.Value as AccountTicket;
            if (tiket != null)
                prifix = string.Format("{0}@{1}@{2}@{3}", tiket.Identity,tiket.Id,tiket.Type, key);

            return prifix;
            //if (!string.IsNullOrEmpty(prifix))
            //    return _cache[prifix + "@" + key.ToString()];
            //else
            //    return null;
        }
    }
}
